/**
 * 
 */
package com.attilax.poster;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.apache.ecs.xhtml.option;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.UnreachableBrowserException;


//import com.attilaax.encode.EncodeX;
import com.attilax.auto.web.WebDriverUtil;
import com.attilax.ex.NotLoginEx;
import com.attilax.exception.ExUtil;
import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.lang.Global;
import com.attilax.net.urlEncode;
import com.attilax.web.UrlX;
import com.google.common.collect.Maps;

/**
 * com.attilax.poster.Poster4gejy
 * 
 * @author attilax 2016年11月22日 下午9:09:28
 */
public class Poster4gejy extends Poseter {
	String pubUrl = "http://www.ganji.com/service_store/manage/post_pub.php?step=2&catid=3_59&domain=zhuzhou&refer=pub";
	public static	FirefoxDriver driver = null;
	private String tel;
	private String pwd;
	String uname = "atlks";
	private String add;
	private String loginUrl = "https://passport.ganji.com/login.php";

	public static void main(String[] args) throws NotLoginEx {
		// Poster4gejy poster4gejy = new Poster4gejy();
		// poster4gejy.uname = "atlks";
		// poster4gejy.pwd = "zzz000";
		// poster4gejy.tel = "010-88888881-777";
		// poster4gejy.add = "我的地址地址地址";
		// poster4gejy.pubWzLogin("标题标题标题标题标题标题标题标题",
		// "内容内容内容内容内容内容内容内容内容内容内容内容");
		System.out.println("--");

		// String f = pathx.webAppPath_jensyegeor() +
		// "/PosterGejy/setPubInfo.js";
		// String js = filex.read(f);
		// System.out.println(js);
		// Poster4gejy.newGetGlbDrivr().

	}
 
	/**
	 * attilax 2016年11月24日 下午6:00:26
	 * 
	 * @return
	 */
	public static Poster4gejy newGetGlbDrivr() {

	//	Map map = Global.globalMap;
		if (Global.globalMap == null)
			Global.globalMap = Maps.newConcurrentMap();
		Poster4gejy poster4gejy = new Poster4gejy(1,3);
	//	poster4gejy.iniDriverV3();
		if (poster4gejy.driver == null) {
			poster4gejy.iniDriverV3();
		}
		
		
		if (poster4gejy.driver == null)
			throw new RuntimeException("drv is null");
		return poster4gejy;

	}

	/**
	 * attilax 2016年11月22日 下午9:23:46
	 * 
	 * @param string
	 * @param string2
	 */
	private void login(String name, String pwd) {

		// driver.get(loginUrl);
		driver.get(loginUrl);
		setLoginInfo(name, pwd);

		driver.findElement(By.cssSelector("input[value='登录赶集']")).click();

		// poster4gejy.login("atlks","zzz000");

	}

	private void loginInPubPageWz(String name, String pwd) {

		// driver.get(loginUrl);
		driver.get(loginUrl);
		setLoginInfo(name, pwd);

		// poster4gejy.login("atlks","zzz000");

	}

	private void setLoginInfo(String name, String pwd) {
		driver.findElement(By.name("login_username")).clear();
		driver.findElement(By.name("login_username")).sendKeys(name);
		driver.findElement(By.name("login_password")).clear();
		driver.findElement(By.name("login_password")).sendKeys(pwd);
	}

	boolean isInLoginForm(String title, String sou) {
		if (title.contains("赶集用户登录"))
			return true;
		if (sou.contains(("自动登录")))
			return true;
		if (sou.contains("登录") && sou.contains("注册") && sou.contains("忘记密码"))
			return true;
		else
			return false;
	}

	// 登录后发布
	public void pubWzLogin() {

		String tit = Global.req.get().getParameter("title");
		String txt = Global.req.get().getParameter("txt");
		if (driver == null)
			iniDriver();
		try {
			driver.get(pubUrl);
		} catch (UnreachableBrowserException e) {
			Global.map.get().put("drv", Optional.empty());
			driver = null;
			iniDriver();
			driver.get(pubUrl);
		}

		// driver.getTitle();jeig yaosi manu op ..laoxsh outtime value ..

		if (isInLoginForm(driver.getTitle(), driver.getPageSource())) {
			// throw new NotLoginEx();

			// loginInPubPageWz(this.uname, this.pwd);
			setLoginInfo(this.uname, this.pwd);
		}

		setPubInfo(tit, txt);

		driver.findElement(By.cssSelector("input[value='登录后发布']")).click();

	}

	// 登录后发布
	public void pubWzLogin(String tit, String txt) {
		driver.get(pubUrl);

		// driver.getTitle();jeig yaosi manu op ..laoxsh outtime value ..

		if (isInLoginForm(driver.getTitle(), driver.getPageSource())) {
			// throw new NotLoginEx();

			// loginInPubPageWz(this.uname, this.pwd);
			setLoginInfo(this.uname, this.pwd);
		}

		setPubInfo(tit, txt);

		driver.findElement(By.cssSelector("input[value='登录后发布']")).click();

	}

	/**
	 * attilax 2016年11月22日 下午9:14:36
	 * 
	 * @param tit
	 * @param txt
	 * @throws NotLoginEx
	 */
	public void pubNlogin(String tit, String txt) {
		driver.get(pubUrl);

		// driver.getTitle();jeig yaosi manu op ..laoxsh outtime value ..
		while (true) {

			if (isInLoginForm(driver.getTitle(), driver.getPageSource())) {
				// throw new NotLoginEx();

				login(this.uname, this.pwd);

			} else
				break;

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		pub(tit, txt);

	}

	private void pub(String tit, String txt) {
		driver.get(pubUrl);

		setPubInfo(tit, txt);
		driver.findElement(By.id("pub_submit")).click();
	}

	private void setPubInfo(String tit, String txt) {
		driver.findElement(By.id("3_59_0")).click(); // check cate
		driver.findElement(By.id("title")).sendKeys(tit);
		driver.findElement(By.id("phone1")).sendKeys(this.tel);
		driver.findElement(By.id("propagandize")).sendKeys(tit);
		// driver.findElement(By.id("description")).sendKeys(txt);
		// //edui-body-container

		String f = pathx.webAppPath_jensyegeor() + "/PosterGejy/setPubInfo.js";
		String js = filex.read(f);
		String script = js.replace("@txt@", txt);
		// window.document.getElementById('editor').value='..xxx'
		// String js = filex.read(f);
		System.out.println(script);
		// driver.ex
		Object obj = exeJs(script);
		// WebElement findElement =
		// driver.findElement(By.cssSelector(".edui-body-container"));
		// findElement.
		// findElement.sendKeys(tit);
		System.out.println("--exe js rzt:" + obj);

		// driver.findElement(By.id("district_id")).sendKeys("0");
		driver.findElement(By.id("address")).sendKeys(this.add);
	}

	public Object exeJs(String script) {
		Object obj = driver.executeScript(script, driver.findElement(By.cssSelector(".edui-body-container")));
		return obj;
	}

	@SuppressWarnings("all")
	public Object exeJs() {

		if (driver == null) {
			// Object object =
			Optional<FirefoxDriver> opt = (Optional<FirefoxDriver>) Global.globalMap.get("drv");
			opt.ifPresent(item -> driver = (FirefoxDriver) item);

		}
		if (driver == null)
			throw new RuntimeException("ex:dirv is null");

		HttpServletRequest req = Global.req.get();
		try {
			req.setCharacterEncoding("utf8");
		} catch (UnsupportedEncodingException e1) {
			ExUtil.throwExV2(e1);
		}
		String script = req.getParameter("cmd");
	 	script=UrlX.decode(script);
	 //	String script_gbk2utf = EncodeX.gbk2utf(script);
	 //	script = script_gbk2utf;
		// String script_utf2gbk=EncodeX.utf2gbk(script);
		System.out.println("--script:" + script);

		Object[] objs = new Object[] {};
		Object obj; // js exe ret value ..is not ret,return null;
		try {
			obj = driver.executeScript(script, objs);
		} catch (UnreachableBrowserException e) {

			iniDriverV2();
			obj = driver.executeScript(script, objs);
		}

		return obj;
	}

	/**
	 * attilax 2016年11月24日 下午8:16:25
	 */
	private void iniDriverV2() {
		// Map map = Global.map.get();
		// Map map = Global.map.get();
		// if(map==null)
		// map=Maps.newConcurrentMap();
		if (Global.globalMap == null)
			Global.globalMap = Maps.newConcurrentMap();
		Map m = Global.globalMap;
		m.put("drv", Optional.empty());
		driver = null;
		iniDriver();
	}

	/**
	 * 
	 */
	public Poster4gejy() {
		iniDriverV3();
	}

	private void iniDriverV3() {
		System.setProperty("webdriver.firefox.bin", pathx.prjParentPath_webrootMode() + "\\Mozilla Firefox\\firefox.exe");
		WebDriverUtil wdu = WebDriverUtil.newx();
		driver = new FirefoxDriver();
		if(Global.globalMap==null)
			Global.globalMap = Maps.newConcurrentMap();
	 
		Global.globalMap.put("drv", Optional.of(driver));
	}

	/**
	 * @param i
	 */
	public Poster4gejy(int i) {
		iniDriver();
	}

	public Poster4gejy(int i,int v2) {
		
	}
	public void iniDriver() {

		if (driver == null) {
			Object object = Global.globalMap.get("drv");
			if (object != null) {
				Optional<FirefoxDriver> opt = (Optional<FirefoxDriver>) object;
				opt.ifPresent(item -> driver = (FirefoxDriver) item);
			}

		}
		if (driver == null) {
			new Poster4gejy();
		}
	}

}
